package com.anhry.www.safety.util;

import org.apache.log4j.Logger;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class Environment {
    private static final Logger LOG = Logger.getLogger(Environment.class);

    // Environment constants.
    private static Environment env;
    private static ResourceBundle envBundle;
    private static String configFile = "ApplicationResources";

    /**
     * Constructor.
     */
    private Environment() {
        LOG.debug("constructor...");
        LOG.debug("loading configFile = " + configFile);

        // Load the application properties file.
        envBundle = ResourceBundle.getBundle(configFile);
    }

    /**
     * Will return an instance if the the instance exists,
     * otherwise it throws a <code>RuntimeException</code>.
     */
    public synchronized static Environment getInstance() {
        if (env == null) {
            env = new Environment();
            LOG.debug("creating new Environment()...");
        }
        return env;
    }

    /**
     * Searches on property taken from properties.
     * PRE-CONDITION: propertyName != null
     */
    public String getProperty(String propertyName) {

        String result = null;
        try {
            result = envBundle.getString(propertyName);
        } catch (MissingResourceException mre) {
            LOG.debug("Couldn't find property: " + propertyName);
        }

        if (result == null) {
            LOG.error("No property found for '" + propertyName + "'.  You may want to check the ApplicationResources.properties file.");
        } else {
            LOG.debug("Found property '" + propertyName + "': " + result);
        }

        return result;
    }
    
    public int getIntProperty(String key) {
    	String result = getProperty(key);
    	int value = 0;
    	if(result != null) {
    		try {
				value = Integer.parseInt(result);
			} catch (NumberFormatException e) {
				LOG.error("Wrong format parameter " + result);
				value = 0;
			}
    	}
    	
    	return value;
    }

    public static void setConfigFile(String configFile) {
        Environment.configFile = configFile;
    }
}
